package com.homework.aop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.homework.mapper.UserMapper;
import com.homework.pojo.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
@Aspect
public class ServiceAop {
    @Autowired
    private UserMapper mapper;
    @Pointcut("@annotation(com.homework.anno.AopAnnoadd)")
    public void add(){}
    @Pointcut("@annotation(com.homework.anno.AopAnnoupdate)")
    public void update(){}
    @Around("add()")
    public int aop(ProceedingJoinPoint joinPoint){
        User user=(User)joinPoint.getArgs()[0];
        DateFormat instance = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String now = instance.format(new Date());
        user.setCreate_time(now);
        user.setModified_time(now);
        user.setModifier(user.getReal_name());
        user.setCreator(user.getReal_name());
        Object[] o={user};
        int b=0;
        System.err.println("test");
        try {
            b=Integer.parseInt( joinPoint.proceed(o).toString());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return  b;
    }
    @Around("update()")
    public int aop2(ProceedingJoinPoint joinPoint) {
        System.out.println("test");
        User user=(User)joinPoint.getArgs()[0];
        QueryWrapper arg = (QueryWrapper) joinPoint.getArgs()[1];
        List u1= mapper.selectList(arg);
        User u2;
        u2=(User)u1.get(0);
            user.setModifier(u2.getReal_name());
            DateFormat instance = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String now = instance.format(new Date());
            user.setModified_time(now);

//        if(u1.getReal_name()!=null)
//            user.setModifier(u1.getReal_name());
//
//        }else {
//            return  0;
//        }
        System.out.println(user);
        Object [] o={user,arg};
        int b=0;
        try {
            b=Integer.parseInt( joinPoint.proceed(o).toString());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return  b;

    }
}
